package com.zmn.oms.third.taobao;

import com.alibaba.fastjson.JSON;
import com.taobao.api.*;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.third.base.util.DutyTimeUtil;
import com.zmn.oms.third.taobao.dto.UnservedWarningDTO;
import com.zmn.oms.third.taobao.dto.api.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 类描述：淘宝API调用器
 *  将业务逻辑和淘宝API调用进行了封装
 *
 * @author LiangHailong
 * @date 2019/06/13 17:08
 */
public class TmallApiInvoker {
    private static final Logger logger = LoggerFactory.getLogger(TmallApiInvoker.class);
    private static final String Api_Invoker = "言而有信";

    private TmallApiInvoker() {};

    /**
     * 【天猫对接】开通消息权限
     * 只在给应用开通消息权限时调用，平时不需要调用
     */
    public static void tmcUserPermit() {
        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmcUserPermitRequest req = new TmcUserPermitRequest();
        TmcUserPermitResponse rsp = null;
        try {
            rsp = client.execute(req, TaobaoTokenManager.getToken());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(rsp.getBody());
    }

    /**
     * 【工单状态同步】改约上门时间
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushOrderDutyTime(OrderStatusParams params) {
        return pushOrderDutyTime(params, null);
    }
    public static TmallApiInvokResult pushOrderDutyTime(OrderStatusParams params, String token) {
        logger.info("【{}-API-订单】<订单状态同步-改约上门时间> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterWorkcardStatusUpdateRequest req = new TmallServicecenterWorkcardStatusUpdateRequest();
        req.setType((byte)1); // type固定写1
        req.setUpdater(Api_Invoker);
        req.setUpdateDate(System.currentTimeMillis());

        if (Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, params.getChannleId())
                || Objects.equals(OrderConsts.CHANNEL_ID_TMALL_PIPE, params.getChannleId())) {
            // 改约上门时间状态码: 天猫无忧购使用9
            req.setStatus((byte)9);
        }
        else {
            // 指派工人状态码: 天猫B端安装使用3
            req.setStatus((byte)3);

            // 天猫B端同步预约时间
            req.setContactName(params.getMasterName());
            req.setContactPhone(params.getMasterPhone());
        }

        req.setWorkcardId(params.getTmallOrderId());
        req.setServiceDate(params.getDutyTime().getTime());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<订单状态同步结束-改约上门时间> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        if (!result.isSuccess()) {
            logger.info("【{}-API-订单】<订单状态同步-改约时间老接口推送失败-再次用新接口推送> OrderId:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    params.getZmnOrderId());
            TmallServicecenterWorkcardReserveRequest reqNew = new TmallServicecenterWorkcardReserveRequest();
            reqNew.setWorkcardId(params.getTmallOrderId());

            String duty = DutyTimeUtil.getDutyTime(DateUtil.toString(params.getDutyTime()));
            List dutyTime = DutyTimeUtil.getDutyList(duty);
            reqNew.setReserveTimeStart(DateUtil.parse(dutyTime.get(0).toString()));
            reqNew.setReserveTimeEnd(DateUtil.parse(dutyTime.get(1).toString()));
            result = apiInvok(client, reqNew, token);
            logger.info("【{}-API-订单】<订单状态同步结束-改约上门时间【{}】新接口> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,duty,
                    params.getZmnOrderId(), result.toString());
        }

        return result;
    }

    /**
     * 【工单状态同步】指派工人，status传9
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushOrderDistribute(OrderStatusParams params) {
        return pushOrderDistribute(params, null);
    }
    public static TmallApiInvokResult pushOrderDistribute(OrderStatusParams params, String token) {
        logger.info("【{}-API-订单】<老接口-订单状态同步-指派工人> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterWorkcardStatusUpdateRequest req = new TmallServicecenterWorkcardStatusUpdateRequest();
        req.setType((byte)1); // type固定写1
        req.setUpdater(Api_Invoker);
        req.setUpdateDate(System.currentTimeMillis());

        if (Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, params.getChannleId())
                || Objects.equals(OrderConsts.CHANNEL_ID_TMALL_PIPE, params.getChannleId())) {
            // 指派工人状态码: 天猫无忧购使用9
            req.setStatus((byte)9);
        }
        else {
            // 指派工人状态码: 天猫B端安装使用3
            req.setStatus((byte)3);

            // 天猫B端同步预约时间
            if (params.getDutyTime() != null) {
                req.setServiceDate(params.getDutyTime().getTime());
            }
        }

        req.setWorkcardId(params.getTmallOrderId());
        req.setContactName(params.getMasterName());
        req.setContactPhone(params.getMasterPhone());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<老接口-订单状态同步结束-指派工人> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        if (!result.isSuccess()) {
            logger.info("【{}-API-订单】<老接口-指派工人推送失败，再次用新接口推送> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    JSON.toJSONString(params));
            TmallServicecenterWorkcardAssignworkerRequest reqNew = new TmallServicecenterWorkcardAssignworkerRequest();
            reqNew.setWorkcardId(params.getTmallOrderId());
            reqNew.setTargetWorkerName(params.getMasterName());
            reqNew.setTargetWorkerMobile(params.getMasterPhone());
            reqNew.setStopOrderTypeCheckReason(params.getStopOrderTypeCheckReason());
            result = apiInvok(client, reqNew, token);
            logger.info("【{}-API-订单】<新接口-订单状态同步结束-指派工人> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    params.getZmnOrderId(), result.toString());
        }

        return result;
    }

    /**
     * 【工单状态同步】取消服务
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushOrderCancel(ApiInvokParams params) {
        return pushOrderCancel(params, null);
    }
    public static TmallApiInvokResult pushOrderCancel(ApiInvokParams params, String token) {
        logger.info("【{}-API-订单】<订单状态同步-取消订单> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterWorkcardStatusUpdateRequest req = new TmallServicecenterWorkcardStatusUpdateRequest();
        req.setType((byte)1); // type固定写1
        req.setUpdater(Api_Invoker);
        req.setUpdateDate(System.currentTimeMillis());
        req.setWorkcardId(params.getTmallOrderId());

        if (Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, params.getChannleId())
                || Objects.equals(OrderConsts.CHANNEL_ID_TMALL_PIPE, params.getChannleId())) {
            // 取消服务状态码: 天猫无忧购使用6
            req.setStatus((byte)6);

            // 取消说明必须是5-50个字符之间
            String remark = params.getRemark();
            if (StringUtils.isBlank(remark)) {
                remark = "服务商取消";
            }
            else if (remark.length() < 5) {
                remark = "服务商取消：" + remark;
            }
            else if (remark.length() > 50) {
                remark = remark.substring(0, 50);
            }
            req.setComments(remark);  // 备注信息，status=6时必传
        }
        else {
            // 取消服务（无需安装）状态码: 天猫B端安装使用11
            req.setStatus((byte)11);
        }


        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<订单状态同步结束-取消订单> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        return result;
    }


    public static void main(String[] args) {
        String token = "62012205a15c54cad49541460c96ZZe7bb425a060d40f622563261712";
        TaobaoTmcConstants.APPKEY = "27577705";
        TaobaoTmcConstants.SECRET = "7b71e52d7a0cb8d20defff143e74a6f7";
        TaobaoTmcConstants.API_URL = "http://gw.api.taobao.com/router/rest";

        // doAddOrUpdateServiceStoreCapacity(token, "update");


        List<KeyValue> list = new ArrayList<>(20);
        list.add(new KeyValue(393119457305702400L, 177254037L));
        list.add(new KeyValue(394537852119035904L, 180618135L));
        list.add(new KeyValue(392040289323200512L, 175767081L));
        list.add(new KeyValue(392041658994143232L, 176032087L));
        list.add(new KeyValue(392041916964806656L, 175925061L));
        list.add(new KeyValue(534693399555481601L, 313968744L));
        list.add(new KeyValue(392277906241363968L, 176387097L));
        list.add(new KeyValue(392039042843160576L, 176124055L));


        for (KeyValue item : list) {
            ApiInvokParams params = new ApiInvokParams();
            params.setServiceCount(1);
            params.setChannleId(31055);
            params.setZmnOrderId(item.orderId);
            params.setTmallOrderId(item.outerId);

            pushOrderComplete(params, token);
        }
    }

    public static class KeyValue {
        private Long orderId;
        private Long outerId;

        public KeyValue(Long orderId, Long outerId) {
            this.orderId = orderId;
            this.outerId = outerId;
        }
    }

    /**
     * 【工单状态同步】回传服务完成
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushOrderComplete(ApiInvokParams params) {
        return pushOrderComplete(params, null);
    }
    public static TmallApiInvokResult pushOrderComplete(ApiInvokParams params, String token) {
        logger.info("【{}-API-订单】<订单状态同步-完成订单> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallApiInvokResult result;
        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        if (Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, params.getChannleId())
                || Objects.equals(OrderConsts.CHANNEL_ID_TMALL_PIPE, params.getChannleId())) {
            // 天猫勤鸽 管道疏通完成
            if (NumberUtil.isNullOrZero(params.getServiceCount())) {
                result = new TmallApiInvokResult();
                result.setSuccess(false);
                result.setMsg("无需同步");
                return result;
            }

            TmallServicecenterWorkcardCompleteRequest req = new TmallServicecenterWorkcardCompleteRequest();
            req.setWorkcardId(params.getTmallOrderId());
            req.setCompleteCount((long) params.getServiceCount());
            req.setSequence(1L);
            result = doApiInvok(client, req, token);

            // 解析结果
            if (result.isSuccess()) {
                TmallServicecenterWorkcardCompleteResponse
                        response = (TmallServicecenterWorkcardCompleteResponse) result.getTaobaoResponse();
                TmallServicecenterWorkcardCompleteResponse.FulfilplatformResult ret = response.getResult();
                if (ret != null) {
                    result.setSuccess(ret.getSuccess());
                    result.setMsg(ret.getMsgInfo());
                }
            }
        }
        // 天猫B端及天猫厂商订单，统一走B端接口
        else {
            TmallServicecenterWorkcardStatusUpdateRequest req = new TmallServicecenterWorkcardStatusUpdateRequest();
            req.setType((byte)1); // type固定写1
            req.setStatus((byte)102);
            req.setUpdater(Api_Invoker);
            req.setUpdateDate(System.currentTimeMillis());
            req.setWorkcardId(params.getTmallOrderId());
            // 服务完成状态码: 天猫B端安装使用5
            req.setStatus((byte)5);
            result = apiInvok(client, req, token);
        }


        logger.info("【{}-API-订单】<订单状态同步结束-完成订单> OrderId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        return result;
    }

    /**
     * 【工单状态同步】回传签到成功
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushSignIn(ApiInvokParams params) {
        return pushSignIn(params, null);
    }

    public static TmallApiInvokResult pushSignIn(ApiInvokParams params, String token) {
        logger.info("【{}-API-订单】<订单状态同步-签到成功> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params.getTmallOrderId()));

        TmallServicecenterWorkcardSigninRequest req = new TmallServicecenterWorkcardSigninRequest();
        req.setWorkcardId(params.getTmallOrderId());

        //Objects.equals(OrderConsts.CHANNEL_ID_TMALL_BUSINESS, params.getChannleId())
        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<订单状态同步结束-签到成功> outerId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        return result;
    }

    /**
     * 【工单状态同步】回传预约失败
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushReserveFailed(ReserveFailedParams params) {
        return pushReserveFailed(params, null);
    }

    public static TmallApiInvokResult pushReserveFailed(ReserveFailedParams params, String token) {
        logger.info("【{}-API-订单】<订单状态同步-预约失败> Params:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterWorkcardReservefailRequest req = new TmallServicecenterWorkcardReservefailRequest();
        req.setWorkcardId(params.getTmallOrderId());
        req.setGmtNextContact(params.getGmtNextContact());
        req.setFailCode(params.getFailCode());
        req.setFailDesc(params.getFailDesc());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<订单状态同步结束-预约失败回传成功> outerId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                params.getZmnOrderId(), result.toString());

        return result;
    }


    /**
     * 【工单状态同步】回传挂起
     *
     * @param params
     * @return
     */
    public static TmallApiInvokResult pushHangUp(ReserveFailedParams params) {
        return pushHangUp(params, null);
    }

    public static TmallApiInvokResult pushHangUp(ReserveFailedParams params, String token) {
        logger.info("【{}-API-回传挂起】<回传挂起> ReserveFailedParams:[{}]", TaobaoTmcConstants.NAME_TMALL, JSON.toJSONString(params));

        TmallServicecenterWorkcardSuspendRequest req = new TmallServicecenterWorkcardSuspendRequest();
        req.setGmtNextContact(params.getGmtNextContact());// 下次联系时间
        req.setWorkcardId(params.getTmallOrderId());
        req.setFailCode(params.getFailCode()); // 挂起原因类型code
        req.setFailDesc(params.getFailDesc()); // 挂起原因

        // 发送请求
        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterWorkcardSuspendResponse
                    response = (TmallServicecenterWorkcardSuspendResponse) result.getTaobaoResponse();
            TmallServicecenterWorkcardSuspendResponse.Result ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getMsgInfo());
            }
        }

        logger.info("【{}-API-回传挂起】<回传挂起结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());
        return result;
    }

    /**
     * 【获取订单】主动获取某个时间段内的订单
     * @param endTime
     * @return
     */
    public static TmallApiInvokResult pullOrders(Date endTime) {
        return pullOrders(endTime, null);
    }
    public static TmallApiInvokResult pullOrders(Date endTime, String token) {
        int limit = 1000 * 60 * 15; // 间隔15分钟
        Date startTime = new Date(endTime.getTime() - limit);
        String startTimeStr = DateUtil.toString(startTime);
        String endTimeStr = DateUtil.toString(endTime);
        logger.info("【{}-API-订单】<获取订单> Time:[{}] - [{}]", TaobaoTmcConstants.NAME_TMALL, startTimeStr, endTimeStr);

        TmallServicecenterTasksSearchRequest req = new TmallServicecenterTasksSearchRequest();
        req.setStart(startTime.getTime());
        req.setEnd(endTime.getTime());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<获取订单结束> Time:[{}] - [{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                startTimeStr, endTimeStr, result.toString());

        return result;
    }

    /**
     * 【查询订单详情】通过交易主订单查询其未拉取的任务类工单
     * @param parentBizOrderId
     * @return
     */
    public static TmallApiInvokResult queryOrderDetail(Long parentBizOrderId) {
        return queryOrderDetail(parentBizOrderId, null);
    }
    public static TmallApiInvokResult queryOrderDetail(Long parentBizOrderId, String token) {
        logger.info("【{}-API-订单】<查询订单详情> parent_biz_order_id:[{}]", TaobaoTmcConstants.NAME_TMALL, parentBizOrderId);

        TmallServicecenterTaskGetRequest req = new TmallServicecenterTaskGetRequest();
        req.setParentBizOrderId(parentBizOrderId);


        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-订单】<查询订单详情结束> parent_biz_order_id:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                parentBizOrderId, result.toString());

        return result;
    }

    /**
     * 【投诉更新】天猫服务平台一键求助单服务商备注更新接口
     * @param taobaoComplaintId
     * @param remark
     * @return
     */
    public static TmallApiInvokResult complaintUpdate(Long taobaoComplaintId, String remark) {
        return complaintUpdate(taobaoComplaintId, remark, null);
    }
    public static TmallApiInvokResult complaintUpdate(Long taobaoComplaintId, String remark, String token) {
        TmallApiInvokResult result = null;

        if (taobaoComplaintId == null || StringUtils.isBlank(remark)) {
            result = new TmallApiInvokResult();
            result.setSuccess(false);
            result.setMsg("参数不全");
            return result;
        }

        logger.info("【{}-API-投诉】<投诉更新> TaobaoComplaintId:[{}], Remark:[{}]", TaobaoTmcConstants.NAME_TMALL,taobaoComplaintId, remark);

        TmallServicecenterAnomalyrecourseRemarkUpdateRequest req = new TmallServicecenterAnomalyrecourseRemarkUpdateRequest();
        req.setTimestamp(System.currentTimeMillis());

        req.setId(taobaoComplaintId);
        req.setRemark(remark);

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        result = apiInvok(client, req, token);

        logger.info("【{}-API-投诉】<投诉更新结束> TaobaoComplaintId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                taobaoComplaintId, result.toString());

        return result;
    }

    /**
     * 【回复工单未服务预警】收到天猫预警后的应答，告诉天猫预警信息的内容我们已知晓
     * @param serviceMonitorMessageId
     * @param remark
     * @return
     */
    public static TmallApiInvokResult replyOrderWarn(Long serviceMonitorMessageId, String remark) {
        return replyOrderWarn(serviceMonitorMessageId, remark, null);
    }
    public static TmallApiInvokResult replyOrderWarn(Long serviceMonitorMessageId, String remark, String token) {
        TmallApiInvokResult result = null;

        logger.info("【{}-API-预警】<回复工单未服务预警> ServiceMonitorMessageId:[{}], Remark:[{}]",
                TaobaoTmcConstants.NAME_TMALL,serviceMonitorMessageId, remark);

        TmallServicecenterServicemonitormessageUpdateRequest req = new TmallServicecenterServicemonitormessageUpdateRequest();
        req.setTimestamp(System.currentTimeMillis());

        req.setStatus(3L); // 返回状态3，告知淘宝消息已读
        req.setServiceMonitorMessageId(serviceMonitorMessageId);
        req.setMemo(remark);

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        result = apiInvok(client, req, token);

        logger.info("【{}-API-预警】<回复工单未服务预警结束> ServiceMonitorMessageId:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                serviceMonitorMessageId, result.toString());

        return result;
    }

    /**
     * 【拉取服务预警】主动拉取未服务预警信息
     * @param endTime
     * @return
     */
    public static TmallApiInvokResult<UnservedWarningDTO> pullOrderWarns(Date endTime) {
        return pullOrderWarns(endTime, null);
    }
    public static TmallApiInvokResult<UnservedWarningDTO> pullOrderWarns(Date endTime, String token) {
        int limit = 1000 * 60 * 15; // 间隔15分钟
        Date startTime = new Date(endTime.getTime() - limit);
        String startTimeStr = DateUtil.toString(startTime);
        String endTimeStr = DateUtil.toString(endTime);
        logger.info("【{}-API-预警】<拉取预警> Time:[{}] - [{}]", TaobaoTmcConstants.NAME_TMALL, startTimeStr, endTimeStr);

        TmallServicecenterServicemonitormessageSearchRequest req = new TmallServicecenterServicemonitormessageSearchRequest();
        req.setStart(startTime.getTime());
        req.setEnd(endTime.getTime());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = apiInvok(client, req, token);

        logger.info("【{}-API-预警】<拉取预警结束> Time:[{}] - [{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                startTimeStr, endTimeStr, result.toString());

        return result;
    }

    /**
     * 添加网点
     * 创建网点信息。对于同一个服务商，通过 service_store_code 保证网点唯一性。需要保证网点不存在才能创建。
     * 地址信息：中文和编码二选一，都填则以编码address_code为准。
     * 错误码 1, 服务商昵称无效 2, 缺少省份 3, 缺少城市 4, 缺少区域 5, 缺少详细地址 6, 传入地址不在标准地址库中，无法解析
     *      7, 缺少网点编码 8, 缺少网点名称 9, 缺少网点电话 10, 网点已存在 11, 网点不存在 12, 系统错误
     * @param params
     * @return
     */
    public static TmallApiInvokResult creatServiceStore(ServiceStoreParams params) {
        return creatServiceStore(params, null);
    }
    public static TmallApiInvokResult creatServiceStore(ServiceStoreParams params, String token) {
        logger.info("【{}-API-网点容量】<添加网点> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL, JSON.toJSONString(params));

        TmallServicecenterServicestoreCreateservicestoreRequest req = new TmallServicecenterServicestoreCreateservicestoreRequest();

        TmallServicecenterServicestoreCreateservicestoreRequest.ServiceStoreDTO
                serviceStoreDTO = new TmallServicecenterServicestoreCreateservicestoreRequest.ServiceStoreDTO();
        serviceStoreDTO.setServiceStoreName(params.getServiceStoreName());
        serviceStoreDTO.setServiceStoreCode(params.getServiceStoreCode());
        serviceStoreDTO.setPhone(params.getPhone());
        serviceStoreDTO.setManagerName(params.getManagerName());
        serviceStoreDTO.setManagerPhone(params.getManagerPhone());
        serviceStoreDTO.setAddressCode(params.getAddressCode());
        serviceStoreDTO.setAddressProvince(params.getAddressProvince());
        serviceStoreDTO.setAddressCity(params.getAddressCity());
        serviceStoreDTO.setAddressDistrict(params.getAddressDistrict());
        serviceStoreDTO.setAddressTown(params.getAddressTown());
        serviceStoreDTO.setAddressDetail(params.getAddressDetail());

        req.setServiceStore(serviceStoreDTO);

        // 发送请求
        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreCreateservicestoreResponse
                    response = (TmallServicecenterServicestoreCreateservicestoreResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreCreateservicestoreResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<添加网点结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 修改网点信息
     * 修改网点信息。对于同一个服务商，通过 service_store_code 保证网点唯一性。需要保证网点存在才能修改。
     * 错误码 1, 服务商昵称无效 2, 缺少省份 3, 缺少城市 4, 缺少区域 5, 缺少详细地址 6, 传入地址不在标准地址库中，无法解析
     *      7, 缺少网点编码 8, 缺少网点名称 9, 缺少网点电话 10, 网点已存在 11, 网点不存在 12, 系统错误
     * @param params
     * @return
     */
    public static TmallApiInvokResult updateServiceStore(ServiceStoreParams params) {
        return updateServiceStore(params, null);
    }
    public static TmallApiInvokResult updateServiceStore(ServiceStoreParams params, String token) {
        logger.info("【{}-API-网点容量】<修改网点> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL, JSON.toJSONString(params));

        TmallServicecenterServicestoreUpdateservicestoreRequest req = new TmallServicecenterServicestoreUpdateservicestoreRequest();
        TmallServicecenterServicestoreUpdateservicestoreRequest.ServiceStoreDto
                serviceStoreDTO = new TmallServicecenterServicestoreUpdateservicestoreRequest.ServiceStoreDto();
        serviceStoreDTO.setServiceStoreCode(params.getServiceStoreCode());  // 需保证service_store_code有值且唯一

        serviceStoreDTO.setServiceStoreName(params.getServiceStoreName());
        serviceStoreDTO.setPhone(params.getPhone());
        serviceStoreDTO.setManagerName(params.getManagerName());
        serviceStoreDTO.setManagerPhone(params.getManagerPhone());
        serviceStoreDTO.setAddressCode(params.getAddressCode());
        serviceStoreDTO.setAddressProvince(params.getAddressProvince());
        serviceStoreDTO.setAddressCity(params.getAddressCity());
        serviceStoreDTO.setAddressDistrict(params.getAddressDistrict());
        serviceStoreDTO.setAddressTown(params.getAddressTown());
        serviceStoreDTO.setAddressDetail(params.getAddressDetail());

        req.setServiceStore(serviceStoreDTO);

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreUpdateservicestoreResponse
                    response = (TmallServicecenterServicestoreUpdateservicestoreResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreUpdateservicestoreResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<修改网点结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 删除网点信息
     * 删除网点信息。对于同一个服务商，通过 service_store_code 删除网点。
     * 错误码 1, 服务商昵称无效 2, 缺少省份 3, 缺少城市 4, 缺少区域 5, 缺少详细地址 6, 传入地址不在标准地址库中，无法解析
     *      7, 缺少网点编码 8, 缺少网点名称 9, 缺少网点电话 10, 网点已存在 11, 网点不存在 12, 系统错误
     * @param params
     * @return
     */
    public static TmallApiInvokResult deleteServiceStore(ServiceStoreParams params) {
        return deleteServiceStore(params, null);
    }
    public static TmallApiInvokResult deleteServiceStore(ServiceStoreParams params, String token) {
        logger.info("【{}-API-网点容量】<删除网点> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL, JSON.toJSONString(params));

        TmallServicecenterServicestoreDeleteservicestoreRequest req = new TmallServicecenterServicestoreDeleteservicestoreRequest();
        req.setServiceStoreCode(params.getServiceStoreCode());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreDeleteservicestoreResponse
                    response = (TmallServicecenterServicestoreDeleteservicestoreResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreDeleteservicestoreResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<删除网点结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 新增网点覆盖的服务
     * 新增网点覆盖的服务，唯一性校验：服务商淘宝账号+网点编码+biz_type 前提是网点要存在， 如果需要新增的网点覆盖的服务已存在，会新增失败。
     * 网点覆盖的服务包含了业务类型(比如电器预约安装)、天猫服务的servicecode列表、授权的类目和品牌
     * @param params
     * @return
     */
    public static TmallApiInvokResult createServiceStoreCoverService(ServiceStoreCoverServiceParams params) {
        return createServiceStoreCoverService(params, null);
    }
    public static TmallApiInvokResult createServiceStoreCoverService(ServiceStoreCoverServiceParams params, String token) {
        logger.info("【{}-API-网点容量】<新增网点覆盖的服务> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterServicestoreCreateservicestorecoverserviceRequest
                req = new TmallServicecenterServicestoreCreateservicestorecoverserviceRequest();
        req.setServiceStoreCode(params.getServiceStoreCode());
        req.setBizType(params.getBizType());
        req.setServiceCodes(params.getServiceCodes());
        req.setCategoryIdsAndBrandIds("[{\"categoryIds\":\"127332019\",\"brandIds\":\"52916195|52913995\"}]");

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreCreateservicestorecoverserviceResponse
                    response = (TmallServicecenterServicestoreCreateservicestorecoverserviceResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreCreateservicestorecoverserviceResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<新增网点覆盖的服务结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 修改网点覆盖的服务
     * 更新网点覆盖的服务，唯一性校验：服务商淘宝账号+网点编码+biz_type 前提是网点要存在， 如果需要新增的网点覆盖的服务不存在，会更新失败。
     * 网点覆盖的服务包含了业务类型(比如电器预约安装)、天猫服务的servicecode列表、授权的类目和品牌
     * @param params
     * @return
     */
    public static TmallApiInvokResult updateServiceStoreCoverService(ServiceStoreCoverServiceParams params) {
        return updateServiceStoreCoverService(params, null);
    }
    public static TmallApiInvokResult updateServiceStoreCoverService(ServiceStoreCoverServiceParams params, String token) {
        logger.info("【{}-API-网点容量】<修改网点覆盖的服务> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterServicestoreUpdateservicestorecoverserviceRequest
                req = new TmallServicecenterServicestoreUpdateservicestorecoverserviceRequest();
        req.setServiceStoreCode(params.getServiceStoreCode());
        req.setBizType(params.getBizType());
        req.setServiceCodes(params.getServiceCodes());
        req.setCategoryIdsAndBrandIds("[{\"categoryIds\":\"127332019\",\"brandIds\":\"52916195|52913995\"}]");

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreUpdateservicestorecoverserviceResponse
                    response = (TmallServicecenterServicestoreUpdateservicestorecoverserviceResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreUpdateservicestorecoverserviceResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<修改网点覆盖的服务结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 新增网点容量
     * 新增网点容量，唯一性校验：服务商淘宝账号+网点编码+biz_type 前提是网点要存在， 如果需要新增的网点容量已存在，会新增失败。
     * 网点容量包含了业务类型(比如电器预约安装)、天猫服务的servicecode列表、类目区域和容量
     * @param params
     * @return
     */
    public static TmallApiInvokResult createServiceStoreCapacity(ServiceStoreCapacityParams params) {
        return createServiceStoreCapacity(params, null);
    }
    public static TmallApiInvokResult createServiceStoreCapacity(ServiceStoreCapacityParams params, String token) {
        logger.info("【{}-API-网点容量】<新增网点容量> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterServicestoreCreateservicestorecapacityRequest
                req = new TmallServicecenterServicestoreCreateservicestorecapacityRequest ();
        req.setServiceStoreCode(params.getServiceStoreCode());
        req.setBizType(params.getBizType());
        req.setServiceCodes(params.getServiceCodes());
        req.setCategoryIdsAndAreaCodesAndCapacity(params.getCategoryIdsAndAreaCodesAndCapacity());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreCreateservicestorecapacityResponse
                    response = (TmallServicecenterServicestoreCreateservicestorecapacityResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreCreateservicestorecapacityResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<新增网点容量结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 更新网点容量
     * 新增网点容量，唯一性校验：服务商淘宝账号+网点编码+biz_type 前提是网点要存在， 如果需要新增的网点容量已存在，会新增失败。
     * 网点容量包含了业务类型(比如电器预约安装)、天猫服务的servicecode列表、类目区域和容量
     * @param params
     * @return
     */
    public static TmallApiInvokResult updateServiceStoreCapacity(ServiceStoreCapacityParams params) {
        return updateServiceStoreCapacity(params, null);
    }
    public static TmallApiInvokResult updateServiceStoreCapacity(ServiceStoreCapacityParams params, String token) {
        logger.info("【{}-API-网点容量】<更新网点容量> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterServicestoreUpdateservicestorecapacityRequest
                req = new TmallServicecenterServicestoreUpdateservicestorecapacityRequest ();
        req.setServiceStoreCode(params.getServiceStoreCode());
        req.setBizType(params.getBizType());
        req.setServiceCodes(params.getServiceCodes());
        req.setCategoryIdsAndAreaCodesAndCapacity(params.getCategoryIdsAndAreaCodesAndCapacity());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreUpdateservicestorecapacityResponse
                    response = (TmallServicecenterServicestoreUpdateservicestorecapacityResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreUpdateservicestorecapacityResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<更新网点容量结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }

    /**
     * 删除网点容量
     * 新增网点容量，唯一性校验：服务商淘宝账号+网点编码+biz_type 前提是网点要存在， 如果需要新增的网点容量已存在，会新增失败。
     * 网点容量包含了业务类型(比如电器预约安装)、天猫服务的servicecode列表、类目区域和容量
     * @param params
     * @return
     */
    public static TmallApiInvokResult deleteServiceStoreCapacity(ServiceStoreCapacityParams params) {
        return updateServiceStoreCapacity(params, null);
    }
    public static TmallApiInvokResult deleteServiceStoreCapacity(ServiceStoreCapacityParams params, String token) {
        logger.info("【{}-API-网点容量】<删除网点容量> ServiceStoreParams:[{}]", TaobaoTmcConstants.NAME_TMALL,
                JSON.toJSONString(params));

        TmallServicecenterServicestoreDeleteservicestorecapacityRequest
                req = new TmallServicecenterServicestoreDeleteservicestorecapacityRequest();
        req.setServiceStoreCode(params.getServiceStoreCode());
        req.setBizType(params.getBizType());

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterServicestoreDeleteservicestorecapacityResponse
                    response = (TmallServicecenterServicestoreDeleteservicestorecapacityResponse)result.getTaobaoResponse();
            TmallServicecenterServicestoreDeleteservicestorecapacityResponse.ResultBase ret = response.getResult();
            if (ret != null) {
                result.setSuccess(ret.getSuccess());
                result.setMsg(ret.getErrorMsg());
            }
        }

        logger.info("【{}-API-网点容量】<删除网点容量结束> Result:[{}]", TaobaoTmcConstants.NAME_TMALL, result.toString());

        return result;
    }


    /**
     * 【查询工人标签】通过工人身份证号和手机号码查询拉取工人的能力标签，用于差异化派单
     * @param isNumber 工人身份证号
     * @param mobile   工人手机号
     * @return
     */
    public static TmallApiInvokResult queryWorkerTaglist(String isNumber, String mobile) {
        return queryWorkerTaglist(isNumber, mobile, null);
    }

    public static TmallApiInvokResult queryWorkerTaglist(String isNumber, String mobile, String token) {
        logger.info("【{}-API-订单】<查询工人的能力标签开始> id_number:[{}],mobile:[{}]", TaobaoTmcConstants.NAME_TMALL, isNumber, mobile);
        TmallServicecenterWorkerTaglistGetRequest req = new TmallServicecenterWorkerTaglistGetRequest();
        req.setIdNumber(isNumber);
        req.setMobile(mobile);

        TaobaoClient client = new DefaultTaobaoClient(TaobaoTmcConstants.API_URL, TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        TmallApiInvokResult result = doApiInvok(client, req, token);

        // 解析结果
        if (result.isSuccess()) {
            TmallServicecenterWorkerTaglistGetResponse
                    response = (TmallServicecenterWorkerTaglistGetResponse) result.getTaobaoResponse();
            if (response != null) {
                result.setSuccess(response.isSuccess());
                result.setMsg(response.getBody());
            }
        }

        logger.info("【{}-API-订单】<查询工人的能力标签结束> id_number:[{}], mobile:[{}], Result:[{}]", TaobaoTmcConstants.NAME_TMALL,
                isNumber, mobile, result.toString());

        return result;
    }

    /**
     * 调用淘宝API，并封装返回结果（已过时，请使用doApiInvok方法代替）
     * @param client
     * @param request
     * @return
     */
    public static TmallApiInvokResult apiInvok(TaobaoClient client, TaobaoRequest request, String token) {
        TaobaoResponse response = _doApiInvok(client, request, token);

        TmallApiInvokResult result = new TmallApiInvokResult();
        result.setSuccess(false);
        result.setTaobaoResponse(response);

        do {
            if (response == null) {
                result.setMsg("请求连接失败。");
                break;
            }
            // 订单状态同步结果
            else if (response instanceof TmallServicecenterWorkcardStatusUpdateResponse) {
                TmallServicecenterWorkcardStatusUpdateResponse resp = (TmallServicecenterWorkcardStatusUpdateResponse)response;
                // 请求失败
                if (resp.getRs() == null) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                else if (!resp.getRs()) {
                    result.setMsg(resp.getErrorMsgInfo());
                    break;
                }
            }
            // 投诉状态同步结果
            else if (response instanceof TmallServicecenterAnomalyrecourseRemarkUpdateResponse) {
                TmallServicecenterAnomalyrecourseRemarkUpdateResponse resp = (TmallServicecenterAnomalyrecourseRemarkUpdateResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                if (!resp.getIsSuccess().booleanValue()) {
                    // TODO -lhl 忽略同步结果
                }
            }
            // 预警消息应答
            else if (response instanceof TmallServicecenterServicemonitormessageUpdateResponse) {
                TmallServicecenterServicemonitormessageUpdateResponse resp = (TmallServicecenterServicemonitormessageUpdateResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterServicemonitormessageUpdateResponse.ResultBase result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getErrorMsg());
                    break;
                }
            }
            // 预警消息主动拉取
            else if (response instanceof TmallServicecenterServicemonitormessageSearchResponse) {
                TmallServicecenterServicemonitormessageSearchResponse resp = (TmallServicecenterServicemonitormessageSearchResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterServicemonitormessageSearchResponse.ResultBase result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getErrorMsg());
                    break;
                }
                // 预警信息类型转换
                List<TmallServicecenterServicemonitormessageSearchResponse.ServiceMonitorMessage> values = result1.getValueList();
                if (!CollectionUtils.isEmpty(values)) {
                    List<UnservedWarningDTO> items = new LinkedList<>();
                    for (TmallServicecenterServicemonitormessageSearchResponse.ServiceMonitorMessage item : values) {
                        UnservedWarningDTO obj = BeanMapper.map(item, UnservedWarningDTO.class);
                        items.add(obj);
                    }
                    result.setItems(items);
                }
            }
            //  签到消息应答
            else if (response instanceof TmallServicecenterWorkcardSigninResponse) {
                TmallServicecenterWorkcardSigninResponse resp = (TmallServicecenterWorkcardSigninResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterWorkcardSigninResponse.Result result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getMsgInfo());
                    break;
                }
            }
            //  预约失败消息应答
            else if (response instanceof TmallServicecenterWorkcardReservefailResponse) {
                TmallServicecenterWorkcardReservefailResponse resp = (TmallServicecenterWorkcardReservefailResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterWorkcardReservefailResponse.Result result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getMsgInfo());
                    break;
                }
            }
            //  预约时间消息应答
            else if (response instanceof TmallServicecenterWorkcardReserveResponse) {
                TmallServicecenterWorkcardReserveResponse resp = (TmallServicecenterWorkcardReserveResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterWorkcardReserveResponse.Result result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getMsgInfo());
                    break;
                }
            }
            //  派单消息应答
            else if (response instanceof TmallServicecenterWorkcardAssignworkerResponse) {
                TmallServicecenterWorkcardAssignworkerResponse resp = (TmallServicecenterWorkcardAssignworkerResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getSubMsg());
                    break;
                }
                // 调用接口返回失败
                TmallServicecenterWorkcardAssignworkerResponse.Result result1 = resp.getResult();
                if (!result1.getSuccess().booleanValue()) {
                    result.setMsg(result1.getMsgInfo());
                    break;
                }
            }
            //  工人标签应答
            else if (response instanceof TmallServicecenterWorkerTaglistGetResponse) {
                TmallServicecenterWorkerTaglistGetResponse resp = (TmallServicecenterWorkerTaglistGetResponse)response;
                // 请求失败
                if (!resp.isSuccess()) {
                    result.setMsg(resp.getMsg());
                    break;
                }
            }
            // 其他
            else if (!response.isSuccess() ) {
                result.setMsg(response.getMsg());
                break;
            }

            result.setSuccess(true);
            result.setMsg(response.getBody());
        } while (false);

        if (!result.isSuccess()) {
            logger.info("【{}-API】<API请求失败> ResponseBody:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    response == null ? result.getMsg() : response.getBody());
        }

        return result;
    }

    private static TaobaoResponse _doApiInvok(TaobaoClient client, TaobaoRequest request, String token) {
        TaobaoResponse response = null;
        try {
            if (StringUtils.isBlank(token)) {
                token = TaobaoTokenManager.getToken();
            }
            response = (TaobaoResponse)client.execute(request, token);
        } catch (ApiException e) {
            logger.error(e.getMessage(), e);
        }
        return response;
    }

    /**
     * 调用淘宝API，并封装返回结果（新）
     * @param client
     * @param request
     * @return
     */
    private static TmallApiInvokResult doApiInvok(TaobaoClient client, TaobaoRequest request, String token) {
        TmallApiInvokResult result = new TmallApiInvokResult();
        result.setSuccess(false);

        try {
            if (StringUtils.isBlank(token)) {
                token = TaobaoTokenManager.getToken();
            }
            TaobaoResponse response = (TaobaoResponse)client.execute(request, token);
            result.setTaobaoResponse(response);

            result.setSuccess(response.isSuccess());
            result.setMsg(response.getBody());

            if (StringUtils.isBlank(result.getMsg())) {
                StringBuilder builder = new StringBuilder();
                if (StringUtils.isNotBlank(response.getMsg())) {
                    builder.append(",msg=").append(response.getMsg());
                }
                if (StringUtils.isNotBlank(response.getMessage())) {
                    builder.append(",message=").append(response.getMessage());
                }
                if (StringUtils.isNotBlank(response.getSubMsg())) {
                    builder.append(",subMsg=").append(response.getSubMsg());
                }
                if (StringUtils.isNotBlank(response.getSubMessage())) {
                    builder.append(",subMessage=").append(response.getSubMessage());
                }

                if (builder.length() > 1) {
                    result.setMsg(builder.substring(1));
                }
            }
        } catch (ApiException e) {
            result.setMsg("请求连接失败。");
            logger.error(e.getMessage(), e);
        }

        return result;
    }





    /**
     *
     * @param token
     * @param addOrUpdate  "add"=创建； "update"=更新
     */
    private static void doAddOrUpdateServiceStoreCapacity(String token, String addOrUpdate) {
        // 清洗网点容量
        ServiceStoreCapacityParams cleanParams = new ServiceStoreCapacityParams();
        cleanParams.setBizType("qinge_home_service");
        cleanParams.setServiceStoreCode("ZMN-1001");
        cleanParams.setServiceCodes("air_conditioner_cleaning|appliance_cleaning");
        cleanParams.setCategoryIdsAndAreaCodesAndCapacity(TaobaoTmcUtil.getCleanString());

        // 维修网点容量
        ServiceStoreCapacityParams repairParams = new ServiceStoreCapacityParams();
        repairParams.setBizType("qinge_home_service");
        repairParams.setServiceStoreCode("ZMN-1002");
        repairParams.setServiceCodes("new_retail_home_appliance_repair|new_retail_air_condition_install");
        repairParams.setCategoryIdsAndAreaCodesAndCapacity(TaobaoTmcUtil.getRepairString());

        // 创建网点容量
        if ("add".equals(addOrUpdate)) {
            System.out.println("============================ 清洗 ==============================");
            createServiceStoreCapacity(cleanParams, token);
            System.out.println("============================ 维修 ==============================");
            createServiceStoreCapacity(repairParams, token);

        }
        // 更新网点容量
        else if ("update".equals(addOrUpdate)) {
            System.out.println("============================ 清洗 ==============================");
            updateServiceStoreCapacity(cleanParams, token);
            System.out.println("============================ 维修 ==============================");
            updateServiceStoreCapacity(repairParams, token);
        }
    }

    private static void doDelServiceStoreCapacity(String token) {
        ServiceStoreCapacityParams params = new ServiceStoreCapacityParams();
        params.setServiceStoreCode("2563261712");
        params.setBizType("qinge_home_service");

        TmallApiInvokResult result = deleteServiceStoreCapacity(params, token);
        System.out.println(result.toString());
    }

    // 添加网点开通服务
    private static void doAddServiceStoreCoverService(String token) {
        ServiceStoreCoverServiceParams params = new ServiceStoreCoverServiceParams();
        params.setBizType("qinge_home_service");
        // appliance_cleaning、air_conditioner_cleaning、new_retail_home_appliance_repair、new_retail_air_condition_install

        /*params.setServiceStoreCode("ZMN-1001");
        params.setServiceCodes("appliance_cleaning|air_conditioner_cleaning");*/

        params.setServiceStoreCode("ZMN-1002");
        params.setServiceCodes("new_retail_home_appliance_repair|new_retail_air_condition_install");

        TmallApiInvokResult result = createServiceStoreCoverService(params, token);
        //TmallApiInvokResult result = updateServiceStoreCoverService(params, token);

        System.out.println(result.toString());
    }

    // 添加网点
    private static void doAddServiceStore(String token) {
        ServiceStoreParams params = new ServiceStoreParams();
        //params.setServiceStoreName("重庆啄木鸟网络科技有限公司");
        //params.setServiceStoreCode("2563261712");   // 重庆啄木鸟网络科技有限公司(已删除)
        params.setServiceStoreName("全国清洗");
        params.setServiceStoreCode("ZMN-1001");   // 全国清洗
        //params.setServiceStoreName("全国维修");
        //params.setServiceStoreCode("ZMN-1002");   // 全国维修
        params.setPhone("18010491280");
        params.setManagerName("潘辰光");
        params.setManagerPhone("18910876825");

        params.setAddressProvince("重庆");
        params.setAddressCity("重庆");
        params.setAddressDistrict("渝北区");
        params.setAddressTown("大湾镇");
        params.setAddressDetail("重庆渝北区两江新区卉竹路2号互联网产业园2期8号楼");
        params.setAddressCode(500112L);

        TmallApiInvokResult result = creatServiceStore(params, token);

        System.out.println(result.toString());
    }

    // 删除网点
    private static void doDelServiceStore(String token) {
        ServiceStoreParams params = new ServiceStoreParams();
        params.setServiceStoreCode("ZMN-1001");

        TmallApiInvokResult result = deleteServiceStore(params, token);
        System.out.println(result.toString());
    }


}
